
<template>  <!--该页面为从设备探索进入的历史探索测试记录页面-->
  <div @keydown="enter($event)">
    <el-breadcrumb separator="/"> <!--面包屑never-->
    <el-breadcrumb-item><i class="el-icon-s-home" style="margin-right: 15px;font-size: 16px"></i>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
	  <div class="info">
      <!-- <el-card shadow="always" class="box-card">
        <el-row align="middle" type="flex">
          <div style="margin-right:10px">
            <span style="align:center" >用户名称</span>
          </div>
          <el-col :span="4">
            <el-row>
              <el-input placeholder="请输入用户名称" clearable prefix-icon="el-icon-search" v-model="searchContent"  size="medium"></el-input>
            </el-row>
          </el-col>
          <el-col :span="16">
          </el-col>
          <el-button type="success"  @click="toSerachUser"  size="small">查询</el-button>
        </el-row>
      </el-card> -->

      <el-card shadow="always" class="box-card">
        <!-- <div slot="header" class="clearfix">
          <el-row align="middle" type="flex">
            <div style="margin-right:10px; width: 30px;">
              <span style="align:center" >查询</span>
            </div>
            <el-col :span="4">
              <el-row>
                <el-input placeholder="请输入查询内容" clearable v-model="searchContent"  size="small"></el-input>
              </el-row>
            </el-col>
            <el-col :span="16">
            </el-col>
            <el-col :span="4">
            <el-button style="float: right;" type="primary"  @click="toSerachUser"  size="small">查询</el-button>
            </el-col>
          </el-row>
        </div> -->
        <div slot="header" class="clearfix">
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item class="roleInput" label="用户信息">
              <el-input v-model.trim="formInline.searchContent" placeholder="请输入查询内容" clearable  size="small"></el-input>
            </el-form-item>
            <el-form-item class="search" label="">
              <el-button @click="toSerachUser" style="float: right;" size="small" type="primary">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-row>
					<el-button class="global_add" type="text" :disabled="btnList.add" @click="dialogVisible = true" size="small" style="float:right; margin-right: 15px; margin-bottom: 5px;">+&nbsp;新增用户</el-button>
				</el-row>
        <el-dialog
          title="新增用户"
          :visible.sync="dialogVisible"
          width="680px"
          >
          <el-form label-width="90px" :model="newUser" :rules="rules" ref="newUser" size="small">
            <el-row>
              <el-col :span="12">
                <el-form-item label="用户名称" prop="nickName">
                    <el-input placeholder="请输入用户名" v-model.trim="newUser.nickName" size="small" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工号" prop="userName">
                  <el-input placeholder="请输入工号" v-model.trim="newUser.userName" size="small" clearable></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="用户角色" prop="roleIdArr"> 
                  <el-select  multiple v-model="newUser.roleIdArr" placeholder="请选择角色" style="width: 100%" clearable>
                    <el-option v-for="item in rolelist" :key="item.role_id" :label="item.role_name" :value="item.role_id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属部门" prop="deptId">
                  <el-select v-model="newUser.deptId" placeholder="请选择部门" style="width: 100%" clearable>
                    <el-option v-for="item in departmentlist" :key="item.dept_id" :label="item.dept_name" :value="item.dept_id" ></el-option>
                  </el-select>
                </el-form-item>
             </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="tel">
                  <el-input placeholder="请输入联系电话" v-model="newUser.tel" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="初始密码" >
                  <el-input placeholder="123456" :disabled="true" clearable></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <!-- <el-col :span="15" style="float:right;margin-right:10px">
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="checkNewUser('newUser')">保存</el-button>
              </el-col> -->
            </el-row> 
          </el-form> 
          <span slot="footer" class="dialog-footer">
                    <el-button class="textBtn" @click="cancel"  size="small">取消</el-button>
                <el-button type="primary" @click="checkNewUser('newUser')"  size="small">保存</el-button>
                  </span>
        </el-dialog>
        <el-table v-loading="dataLoading" stripe :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)" border style="width: 100%">
          <el-table-column  type="index" label="#" :index = '(index) =>{return (index + 1) + (currentPage - 1) * pagesize}' width="70" align="center"></el-table-column>
          <el-table-column align="center" prop="nickname" label="用户名称" :span="4"></el-table-column>
          <el-table-column align="center" prop="username" label="工号" :span="4"></el-table-column>
          <el-table-column align="center" prop="telephone" label="联系电话" :span="4"></el-table-column>
          <el-table-column align="center" prop="dept_name" label="所属部门" :span="5"></el-table-column>
          <el-table-column align="center" prop="role_nameStr" label="角色" :span="5"></el-table-column>
          <el-table-column align="center" label="操作"  :span="3">
            <template slot-scope="scope">
              <el-button class="global_edit" @click="toEditUSer(scope.$index, scope.row)" type="text" size="small" style="color:#6C59DD" :disabled="btnList.edit">编辑</el-button>
                
              <el-button class="global_delete" type="text" size="small" @click="toDeleteUser(scope.$index, scope.row)" style="color:#D9001B;" :disabled="btnList.delete">删除</el-button>
              <el-button class="global_reset" type="text" size="small" @click="toResetPwd(scope.$index, scope.row)" :disabled="btnList.reset">重置密码</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination class="pagination" background :current-page.sync="currentPage" :hide-on-single-page="showPagination" :page-size="pagesize" layout="prev, pager, next" :total="tableData.length"></el-pagination>
      </el-card>
      <el-dialog
                  title="编辑用户"
                  :visible.sync="editUserdialog"
                  width="450px"
                  >
                  <el-form  label-width="80px" :model="editUser" :rules="rules" ref="editUser"  size="small">
                    <el-form-item label="用户名" prop="nickName" >
                      <el-input placeholder="请输入用户名" v-model="editUser.nickName" style="width: 90%" size="small" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="工号" prop="userName">
                      <el-input placeholder="请输入工号" v-model="editUser.userName"  style="width: 90%" size="small" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="部门" prop="deptId">
                      <el-select v-model="editUser.deptId" placeholder="请选择部门"   style="width: 90%" clearable>
                        <el-option v-for="item in departmentlist" :key="item.dept_id" :label="item.dept_name" :value="item.dept_id"></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item  label="角色" prop="roleNameArr"> 
                      <el-select  multiple v-model="editUser.roleNameArr" placeholder="请选择角色"  style="width: 90%" clearable>
                        <el-option v-for="item in rolelist" :key="item.role_id" :label="item.role_name" :value="item.role_name"></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="联系电话" prop="tel">
                      <el-input placeholder="请输入联系电话" v-model="editUser.tel" clearable  style="width: 90%"></el-input>
                    </el-form-item>
                      <!-- <el-form-item>
                          <el-button @click="editUserdialog = false">取消</el-button>
                          <el-button type="primary" @click="checkEditUser('editUser')">保存</el-button>
                      </el-form-item>                   -->
                  </el-form> 
                  <span slot="footer" class="dialog-footer">
                    <el-button class="textBtn" @click="editUserdialog = false"  size="small">取消</el-button>
                    <el-button type="primary" @click="checkEditUser('editUser')"  size="small">保存</el-button>
                  </span>
                </el-dialog>
    </div>
  </div>
</template>
<script>
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 引入需要用到的第三方nodejs库，如日期计算等
// 需要先通过npm安装第三方组件包，然后在代码中使用
// npm install xxx :settings="chartSettings"
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// import moment from 'moment';
// import ElementUI from 'element-ui';
//import 'element-ui/lib/theme-chalk/index.css';
import roleBtn from '../../public/means'

export default {
	data() {
    let validateTel = (rule, value, callback) => {
      let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
        if (!reg.test(value)) {
          callback(new Error('手机号码格式不正确'));
        }
        callback()
        
      };
      let validateNickName = (rule, value, callback) => {
      let reg = /^[\u4e00-\u9fa5]{1,5}$/
        if (!reg.test(value)) {
          callback(new Error('用户名称格式不正确'));
        }
        callback()
 
      };
      let validateUserName = (rule, value, callback) => {
      let reg = /^[0-9]{1,8}$/
        if (!reg.test(value)) {
          callback(new Error('工号格式不正确'));
        }
         callback()
 
      };
		return {
      formInline: {
        searchContent: '',
      },
      dialogVisible: false,
      editUserdialog:false,
      // searchContent:'',
      showPagination: true,     //分页显示
      currentPage: 1,           //从第几页开始显示
      pagesize: 10,              //每页多少行数据
      dataLoading: false,
      menu_id: 9,
      btnList: {
        add: false,
        edit: false,
        delete: false,
        reset: false
      },
      newUser:{
        nickName:'',
        userName:'',
        deptId:'',
        roleIdArr:[],
        tel:''
      },
      editUser:{
        userId:'',
        nickName:'',
        userName:'',
        deptId:'',
        roleNameArr:[],
        tel:''
      },
      rules:{
        nickName:[
          {required: true, message: '请输入用户名', trigger: 'blur' },
          {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'},
          { validator: validateNickName, trigger: 'blur' },
        ],
        userName:[{required: true, message: '请输入工号', trigger: 'blur' },{validator: validateUserName, trigger: 'blur' }],
        deptId:[{required: true, message: '请选择部门', trigger: 'blur' },],
        roleIdArr:[{required: true, message: '请选择角色', trigger: 'blur' },],
        roleNameArr:[{required: true, message: '请选择角色', trigger: 'blur' },],
        tel:[{required: true, message: '请输入联系电话', trigger: 'blur' },{ validator: validateTel, trigger: 'blur' }],
        
      },
      tableData: [],
      rolelist:[],
      departmentlist:[]
		};
	},
	methods: {
    //查询用户
    toSerachUser(){
      this.getAllUser();
    },
    //点击编辑按钮，赋给editUser原来的值并显示
    toEditUSer(index,row){
      this.editUserdialog=true;
      this.editUser.nickName=row.nickname;
      this.editUser.userName=row.username;
      this.editUser.deptId=row.dept_id;
      this.editUser.userId=row.user_id;
      if(row.role_nameStr != null)
        this.editUser.roleNameArr=row.role_nameStr.split(',');
      else
        this.editUser.roleNameArr=new Array();

      if(row.telephone != null)
        this.editUser.tel=row.telephone;
      else
        this.editUser.tel='';
    },
    //有查询内容就查询，没有就查询所有用户
    async getAllUser(){
      this.dataLoading = true;
      const params = {
        'searchContent': this.formInline.searchContent,
      }
      console.log(params);
      const ret = await this.$http.get("/userManagement/getAllUser",{params,});
      // //通过rolelist，将查出来的role_id字符串拼成rolename
      // for(let i=0;i<ret.result.length;i++){
      //   let arr=ret.result[i].roles.split(',');
      //   ret.result[i].role_name='';
      //   for(let j=0;j<arr.length;j++){
      //     for(let k=0;k<this.rolelist.length;k++){  
      //       if(arr[j]==this.rolelist[k].role_id)
      //         ret.result[i].role_name+=this.rolelist[k].role_name+',' ;
      //     }
      //   }
      //   ret.result[i].role_name=ret.result[i].role_name.slice(0,ret.result[i].role_name.length-1)
      // }
      this.tableData = ret.result;
      this.dataLoading = false;
    },
    //删除用户确认
    toDeleteUser(index,row){
      this.$confirm('确定删除该用户,此操作不可撤销', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(({ result }) => {
        if(!result){
					this.deleteUser(row.user_id);
				}
      }).catch(() => {
        });
    },
    //删除用户
    async deleteUser(user_id){
      let ret;
      const params = {
        'user_id':user_id
      }
      ret = await this.$http.delete("/userManagement/deleteUser",{params,});
      if(ret.code === 200){
      this.$message({
          showClose: true,
          message: ret.message,
          type: 'success'
        });
      }
      this.getAllUser();
    },
    //重置用户密码确认
    toResetPwd(index,row){
      this.$confirm('确定重置该用户密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(({ result }) => {
        if(!result){
					this.resetPwd(row.user_id);
				}
      }).catch(() => {
        });
    },
    //重置用户密码
    async resetPwd(user_id){
      let ret;
      const params = {
        'user_id': user_id
      }
      ret = await this.$http.post("/userManagement/resetPwd",params);
      if(ret.code === 200){
      this.$message({
          showClose: true,
          message: '重置成功',
          type: 'success'
        });
      }
      this.getAllUser();
    },
    //获取所有部门
    async getAllDepartment(){
      const ret = await this.$http.get("/userManagement/getAllDepartment");
      this.departmentlist = ret.result;
    },
     //获取所有角色
    async getAllRole(){
      const ret = await this.$http.get("/userManagement/getAllRole");
      this.rolelist = ret.result;
    },
    //修改角色数据校验
    checkEditUser(){
      this.$refs.editUser.validate(valid => {
        console.log(valid);
        if(valid) {
          let check = true;
          for(let i = 0;i < this.tableData.length;i++){
            if (this.editUser.userId !== this.tableData[i].user_id) {
               if(this.editUser.userName == this.tableData[i].username){
                  this.$message.closeAll();
                  this.$message({ message: '工号不可重复！', type: 'error', duration: 1000 });
                  check = false;
                }
            }
          }
          if(check)
            this.saveEditUser();
        }
      })
      // this.$message.closeAll();
      // if(this.editUser.nickName == ""||this.editUser.nickName.length > 10||this.editUser.nickName.length < 2){
      //   this.$message({ message: '请输入合适的用户名！', type: 'error', duration: 1000 });
      // } else if (this.editUser.userName == ""){
      //   this.$message({ message: '请输入账号！', type: 'error', duration: 1000 });
      // } else if(this.editUser.deptId == ""){
      //   this.$message({ message: '请选择一个部门！', type: 'error', duration: 1000 });
      // }else if(this.editUser.roleNameArr.length == 0){
      //   this.$message({ message: '请至少选择一个角色！', type: 'error', duration: 1000 });
      // }else if(this.editUser.tel.length != 11||this.editUser.tel == null){
      //   this.$message({ message: '请输入正确的联系电话！', type: 'error', duration: 1000 });
      // }else{
      //   this.saveEditUser();
      // }
    },
    //修改角色
    async saveEditUser(){
        let roleIdArr=[];
        for (let i=0;i<this.editUser.roleNameArr.length;i++){    //roleNameArr是角色名称的数组，把相应的roleId写入roleIdArr数组里
          for(let j=0;j<this.rolelist.length;j++){
            if(this.editUser.roleNameArr[i]==this.rolelist[j].role_name)
              roleIdArr.push(this.rolelist[j].role_id);
          }
        }
        const params =  {
          'nickname': this.editUser.nickName,
          'username': this.editUser.userName,
          'dept_id': this.editUser.deptId,
          'roleIdArr': roleIdArr, 
          'user_id': this.editUser.userId,
          'tel': this.editUser.tel
        };
        const ret = await this.$http.post("/userManagement/saveEditUser",params);
				console.info(ret);
        if(ret.code === 200){
        this.$message({
          showClose: true,
          message: '修改成功',
            type: 'success'
          });
        }
        this.$refs['editUser'].resetFields();
        this.editUserdialog = false;
        this.getAllUser();
       
    },
    //新增角色数据校验
    checkNewUser(){
      this.$refs.newUser.validate(valid => {
        console.log(valid);
        if(valid) {
          let check = true;
          for(let i = 0;i < this.tableData.length;i++){
          if(this.newUser.userName == this.tableData[i].username){
            this.$message.closeAll();
            this.$message({ message: '工号不可重复！', type: 'error', duration: 1000 });
            check = false;
          }
         }
          if(check)
            this.saveNewUser();
        }
      })
      // this.$message.closeAll();13363902879
      // if(this.newUser.nickName == ""||this.newUser.nickName.length > 10||this.newUser.nickName.length < 2){
      //   this.$message({ message: '请输入合适的用户名！', type: 'error', duration: 1000 });
      // } else if (this.newUser.userName == ""){
      //   this.$message({ message: '请输入账号！', type: 'error', duration: 1000 });
      // } else if(this.newUser.deptId == ""){
      //   this.$message({ message: '请选择一个部门！', type: 'error', duration: 1000 });
      // }else if(this.newUser.roleIdArr.length == 0){
      //   this.$message({ message: '请至少选择一个角色！', type: 'error', duration: 1000 });
      // }else if(this.newUser.tel.length != 11||this.newUser.tel == null){
      //   this.$message({ message: '请输入正确的联系电话！', type: 'error', duration: 1000 });
      // }else{
      //   this.saveNewUser();
      // }
    },  
    //新增角色
    async saveNewUser(){
      const params = this.newUser;
      const ret = await this.$http.post("/userManagement/saveNewUser",params);
        if(ret.code === 200){
          this.$message({
            showClose: true,
            message: '添加成功',
            type: 'success'
          });
          this.$refs['newUser'].resetFields();
          this.dialogVisible = false;
          this.getAllUser();
        }
      
    },
    cancel() {
      this.$refs.newUser.resetFields()
      this.dialogVisible = false
    },
    enter(ev) {
			//回车事件
			if (ev.keyCode === 13) {
				this.toSerachUser();
			}
      }
  },
	mounted() {
    this.getAllDepartment();
    this.getAllRole();
    this.getAllUser();

	},
  async created() {
    const role_id = JSON.parse(sessionStorage.getItem('userInfo')).role_id;
      if(role_id){
      // 获取按钮权限状态
      let arr = await roleBtn.roleBtnList(role_id, this.menu_id)
      this.btnList = arr
    }
  }
};
</script>
<style lang="scss" scoped>
@import "./UserManagement.scss";
</style>